//WYSIWYG 0.0.6
(function($){
    //Get iframe document
    $.fn.wysiwyg_document=function(){
        var element=this.get(0);
        if (element.nodeName.toLowerCase()=='iframe'){
            return element.contentWindow.document;
        }
        return this;
    };
    $.fn.wysiwyg_selection=function(){
        var element=this.get(0);
        if (element.contentWindow.document.selection){
            return element.contentWindow.document.selection.createRange().text;
        }
        else{
            return element.contentWindow.getSelection().toString();
        }
    };
    
    $.wysiwyg_options=[];
    $.fn.wysiwyg=function(opt){
        if($(this).attr('wysiwyg')!=undefined){
            return $(this).wysiwyg_api(opt, param);
        }
        else{
            $(this).wysiwyg_init(opt);
            return '';
        }
    }
    $.fn.wysiwyg_init=function(opt){
        var index=$.wysiwyg_options.length;
        $.wysiwyg_options[index]=$.extend({
            'height': 300,
            'tools':[
                'bold', 'italic', 'strike', 'underline', 'separator',
                'left', 'center', 'right', 'full', 'separator',
                'undo', 'redo', 'separator',
                'ol', 'ul', 'hr', 'separator',
                'link', 'image', 'separator',
                'text', 'html'
            ]
        },opt);
        $(this).attr('wysiwyg', index);
        var options=$.wysiwyg_options[index];
        
        $(this).addClass('ui-corner-all');
        $(this).prepend('<div class="top"><ul class="panel"></ul><iframe src="javascript:false;" frameborder="0"></iframe></div>');
        
        var textarea=$(this).find('textarea');
        var iframe=$(this).find('iframe');
        var iframeDoc=iframe.wysiwyg_document();
        var panel=$(this).find('.panel');
        
        var html='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><base href="'+$.symbiosis.url+'" /><link rel="stylesheet" href="design/'+$.symbiosis.design+'/files/css/wysiwyg.css" type="text/css" media="screen" />STYLE_SHEET</head><body style="margin: 0px;">INITIAL_CONTENT</body></html>';
        var style="<style>body:after{content: '.';display: block;clear: both;visibility: hidden;height: 0;}</style>";
        
        if(textarea.val()===''||textarea.val()==='<br/>'||textarea.val()===' '||textarea.val()==='\n') textarea.val('<p><br/></p>');
        panel.addClass('ui-widget-header').addClass('ui-corner-all');
        iframeDoc.open();
        iframeDoc.write(html
                    .replace(/INITIAL_CONTENT/, function() { return ' '; })
                    .replace(/STYLE_SHEET/, function() { return style; })
                    );
        iframeDoc.close();
        iframeDoc.designMode='on';
        
        t2i();
        width=textarea.get(0).width||textarea.get(0).clientWidth;
        
        iframe.width(width);
        iframe.height(options.height);
        textarea.hide();
        
        
        textarea.keyup(function(){
            val=textarea.val();
            if(val===''||val==='<br/>'||val==='\n'||val===' '){
                textarea.val('<p><br/></p>');
                t2i();
                textarea.focus();
            }
            t2i();
            height=textarea.get(0).height||textarea.get(0).clientHeigt;
            textarea.height(height);
        });
        $(iframeDoc).keyup(function(){
            i2t();
            val=textarea.val();
            if(val===''||val==='<br/>'||val==='\n'||val===' '){
                textarea.val('<p><br/></p>');
                t2i();
                iframe.focus();
            }
        });
        
        function i2t(){
            html=$(iframeDoc).find('body').html();
            html=html.replace(/<br>/igm, "<br/>");
            html=html.replace(/<hr>/igm, "<hr/>");
            html=html.replace(/<img ([a-zA-Z0-9_=\-\/; ":.]*)>/igm, "<img $1 />");
            textarea.val(html);
        }
        function t2i(){
            $(iframeDoc).find('body').html(textarea.val());
            $(iframeDoc).find('a').wysiwyg_a();
            $(iframeDoc).find('a>img').parent().wysiwyg_img();
        }
        function withCss(){
            if ($.browser.mozilla){
                try{
                    iframe.execCommand('styleWithCSS', false, false);
                }
                catch(e){
                    try{
                        iframe.execCommand('useCSS', false, true);
                    }
                    catch(e){}
                }
            }
        }
        
        
        var tools={
            bold: function(){
                iframeDoc.execCommand('Bold', false, []);
                i2t();
                iframe.focus();
            },
            italic: function(){
                iframeDoc.execCommand('Italic', false, []);
                i2t();
                iframe.focus();
            },
            strike: function(){
                iframeDoc.execCommand('strikeThrough', false, []);
                i2t();
                iframe.focus();
            },
            underline: function(){
                iframeDoc.execCommand('Underline', false, []);
                i2t();
                iframe.focus();
            },
            left: function(){
                iframeDoc.execCommand('JustifyLeft', false, []);
                i2t();
                iframe.focus();
            },
            right: function(){
                iframeDoc.execCommand('JustifyRight', false, []);
                i2t();
                iframe.focus();
            },
            center: function(){
                iframeDoc.execCommand('JustifyCenter', false, []);
                i2t();
                iframe.focus();
            },
            full: function(){
                iframeDoc.execCommand('JustifyFull', false, []);
                i2t();
                iframe.focus();
            },
            undo: function(){
                iframeDoc.execCommand('Undo', false, []);
                i2t();
                iframe.focus();
            },
            redo: function(){
                iframeDoc.execCommand('Redo', false, []);
                i2t();
                iframe.focus();
            },
            ol: function(){
                iframeDoc.execCommand('InsertOrderedList', false, []);
                i2t();
                iframe.focus();
            },
            ul: function(){
                iframeDoc.execCommand('InsertUnorderedList', false, []);
                i2t();
                iframe.focus();
            },
            hr: function(){
                iframeDoc.execCommand('InsertHorizontalRule', false, []);
                i2t();
                iframe.focus();
            },
            link: function(){
                wind='#wysiwyg-url-'+index;
                if(!$(wind).length){
                    var value='<div id="wysiwyg-url-'+index+'">'
                    +'<div><label>Title:</label><input class="title" type="text" /></div>'
                    +'<div><label>URL:</label><input class="url" name="url" type="text" /></div>'
                    +'</div>';
                    $('#windows').append(value);
                    $(wind).dialog({
                        autoOpen: true,
                        width: 300,
                        buttons: {
                            "Cancel": function(){
                                $(this).dialog("close");
                            },
                            "Ok": function() {
                                var url = $(wind+' .url').val();
                                var title = $(wind+' .title').val();
                                iframeDoc.execCommand('unlink', false, []);
                                if (url && url.length > 0 ){
                                    if(title=='') title=url;
                                    iframeDoc.execCommand('createLink', false, url);
                                    $(iframeDoc).find('a').each(function(){
                                        if(!$(this).attr('title')){
                                            $(this).attr('title', title);
                                            $(this).wysiwyg_a(index);
                                        }
                                    });
                                }
                                $(wind+' .url').val('');
                                $(wind+' .title').val('');
                                $(this).dialog("close");
                                i2t();
                                iframe.focus();
                            }
                        },
                        closeOnEscape: true
                    });
                }
                else{
                    $(wind).dialog('open');
                    iframe.focus();
                }
            },
            image: function(){
                wind='#wysiwyg-image-'+index;
                if(!$(wind).length){
                    var value='<div id="wysiwyg-image-'+index+'">'
                    +'<div class="tabs"><form><ul>'
                    +'<li><a href="#wysiwyg-image-upload-'+index+'">Upload</a></li>'
                    +'<li><a href="#wysiwyg-image-url-'+index+'">Url</a></li>'
                    +'<li><a href="#wysiwyg-image-resize-'+index+'">Resize</a></li>'
                    +'<li><a href="#wysiwyg-image-options-'+index+'">Options</a></li>'
                    +'</ul>'
                    +'<div id="wysiwyg-image-upload-'+index+'"><input class="image" id="wysiwyg-image-upload-input-'+index+'" name="image" type="file" /></div>'
                    +'<div id="wysiwyg-image-url-'+index+'"><input class="url" type="text" /></div>'
                    +'<div id="wysiwyg-image-resize-'+index+'"><div class="size">Width: <b></b>, height: <b></b></div><div class="width"></div><div class="img" style="width: 540px; height: 400px; overflow: scroll;"></div></div>'
                    +'<div id="wysiwyg-image-options-'+index+'">'
                    +'<div><label>Margin:</label><input type="text" class="margin" /></div>'
                    +'<div><label>Align:</label><select class="align"><option value="none">None</option><option value="left">Left</option><option value="right">Right</option><option value="center">Center</option></select></div>'
                    +'</div>'
                    +'</form></div>';
                    $('#windows').append(value);
                    $('#wysiwyg-image-resize-'+index).hide();
                    
                    $(wind+' .tabs').tabs();
                    $(wind).dialog({
                        autoOpen: true,
                        position: ['center',80],
                        width: 600,
                        closeOnEscape: true,
                        open: function(event, ui){
                            $('#wysiwyg-image-upload-'+index).unbind('change').change(function(){
                                $.ajaxFileUpload({
                                    url:'?page=$&upload&name=image&dir=uploads/images/',
                                    secureuri:false,
                                    fileElementId:'wysiwyg-image-upload-input-'+index,
                                    dataType: 'json',
                                    success: function (data, status){
                                        if(typeof(data.error) != 'undefined'){
                                            if(data.error != ''){
                                                alert(data.error);
                                            }
                                            else{
                                                $(wind+' .url').val(data.url.substr(1));
                                                var img=new Image();
                                                img.onload=function(){
                                                    $('#wysiwyg-image-resize-'+index).show();
                                                    $('#wysiwyg-image-resize-'+index+' .img').append('<img src="'+data.url+'" width="'+img.width+'" height="'+img.height+'" />');
                                                    $('#wysiwyg-image-resize-'+index+' .size b:first').html(img.width);
                                                    $('#wysiwyg-image-resize-'+index+' .size b:last').html(img.height);
                                                    $('#wysiwyg-image-resize-'+index+' .width').slider({
                                                        range: "min",
                                                        min: 1,
                                                        max: img.width,
                                                        value: img.width,
                                                        slide: function(event, ui){
                                                            $('#wysiwyg-image-resize-'+index+' .img img').width(ui.value);
                                                            height=parseInt((img.height/img.width)*ui.value);
                                                            $('#wysiwyg-image-resize-'+index+' .img img').height(height);
                                                            $('#wysiwyg-image-resize-'+index+' .size b:first').html(ui.value);
                                                            $('#wysiwyg-image-resize-'+index+' .size b:last').html(height);
                                                        }
                                                    });
                                                }
                                                img.src=data.url;
                                            }
                                        }
                                    },
                                    error: function (data, status, e){
                                        alert(e);
                                    }
                                });
                            });
                        },
                        buttons: {
                            "Cancel": function(){
                                $(this).dialog("close");
                            },
                            "Ok": function() {
                                url = $(wind+' .url').val();
                                t=$(this);
                                $.ajax({
                                    data:{
                                        'resize': url,
                                        'width': $('#wysiwyg-image-resize-'+index+' .size b:first').html(),
                                        'postfix': '_m'
                                    },
                                    success:function(r){
                                        if(r.ok!=undefined){
                                            url_m=r.ok;
                                            if (url_m&&url_m.length>0){
                                                var img=new Image();
                                                img.onload=function(){
                                                    iframeDoc.execCommand('insertImage', false, url_m);
                                                    align=t.find('.align').val();
                                                    margin=t.find('.margin').val();
                                                    $(iframeDoc).find('img').each(function(){
                                                        if(!$(this).attr('align')){
                                                            $(this).after('<a href="'+url+'"><img src="'+url_m+'" align="'+align+'" style="margin:'+margin+'px;" /></a>');
                                                            $(this).next().wysiwyg_img(index);
                                                            $(this).remove();
                                                            setTimeout(function(){
                                                                i2t();
                                                            }, 100);
                                                        }
                                                    });
                                                    t.dialog("close");
                                                    i2t();
                                                }
                                                img.src=url_m;
                                                
                                            }
                                        }
                                    }
                                });
                            }
                        },
                        close: function(){
                            $(wind+' .image').val('');
                            $(wind+' .url').val('');
                            $(wind+' .margin').val('');
                            $('#wysiwyg-image-resize-'+index).hide();
                        }
                    });
                }
                else{
                    $(wind).dialog('open');
                }
            },
            text:function(){
                iframeDoc.execCommand('removeFormat', false, []);
                i2t();
                iframeDoc.execCommand('unlink', false, []);
            },
            html:function(){
                if(textarea.css('display')=='none'){
                    textarea.show();
                }
                else{
                    textarea.hide();
                }
            }
        }
        
        for(key in options.tools){
            var val=options.tools[key];
            if(val!="separator"){
                panel.append('<li><a href="#'+val+'" class="'+val+'"></a></li>');
                panel.find('a:last').click(function(){
                    func=tools[$(this).attr('href').substr(1)];
                    if(func!=undefined){
                        //withCss();
                        iframe.focus();
                        func();
                    }
                    return false;
                });
            }
            else{
                panel.append('<li class="separator"></li>');
            }
        }
    }
    $.fn.wysiwyg_img=function(index){
        $(this).unbind('dblclick').dblclick(function(){
            wind='#wysiwyg-image-edit-'+index;
            var image=$(this);
            if(!$(wind).length){                
                var value='<div id="wysiwyg-image-edit-'+index+'">'
                +'<div class="tabs"><form><ul>'
                +'<li><a href="#wysiwyg-image-edit-resize-'+index+'">Resize</a></li>'
                +'<li><a href="#wysiwyg-image-edit-options-'+index+'">Options</a></li>'
                +'</ul>'
                +'<div id="wysiwyg-image-edit-resize-'+index+'"><div class="size">Width: <b></b>, height: <b></b></div><div class="width"></div><div class="img" style="width: 540px; height: 400px; overflow: scroll;"></div></div>'
                +'<div id="wysiwyg-image-edit-options-'+index+'">'
                +'<div><label>Margin:</label><input type="text" class="margin" /></div>'
                +'<div><label>Align:</label><select class="align"><option value="none">None</option><option value="left">Left</option><option value="right">Right</option><option value="center">Center</option></select></div>'
                +'</div>'
                +'</form></div>';
                $('#windows').append(value);
                
                $(wind+' .tabs').tabs();
                $(wind).dialog({
                    autoOpen: true,
                    position: ['center',80],
                    width: 600,
                    closeOnEscape: true,
                    open: function(event, ui){
                        var url=image.attr('href');
                        var url_m=image.find('img').attr('src');
                        var margin=parseInt(image.find('img').css('margin-top'));
                        var align=image.find('img').attr('align');
                        
                        $('#wysiwyg-image-edit-resize-'+index).hide();
                        $('#wysiwyg-image-edit-options-'+index+' .margin').val(margin);
                        $('#wysiwyg-image-edit-options-'+index+' .align option').each(function(){
                            if($(this).attr('value')==align) $(this).attr('selected', true);
                        });
                        
                        var img=new Image();
                        img.onload=function(){
                            var img_m=new Image();
                            img_m.onload=function(){
                                $('#wysiwyg-image-edit-resize-'+index).show();
                                $('#wysiwyg-image-edit-resize-'+index+' .img').html('<img src="'+url+'" width="'+img_m.width+'" height="'+img_m.height+'" />');
                                $('#wysiwyg-image-edit-resize-'+index+' .size b:first').html(img_m.width);
                                $('#wysiwyg-image-edit-resize-'+index+' .size b:last').html(img_m.height);
                                $('#wysiwyg-image-edit-resize-'+index+' .width').slider({
                                    range: "min",
                                    min: 1,
                                    max: img.width,
                                    value: img_m.width,
                                    slide: function(event, ui){
                                        $('#wysiwyg-image-edit-resize-'+index+' .img img').width(ui.value);
                                        height=parseInt((img.height/img.width)*ui.value);
                                        $('#wysiwyg-image-edit-resize-'+index+' .img img').height(height);
                                        $('#wysiwyg-image-edit-resize-'+index+' .size b:first').html(ui.value);
                                        $('#wysiwyg-image-edit-resize-'+index+' .size b:last').html(height);
                                    }
                                });
                            }
                            img_m.src=url_m;
                        }
                        img.src=url;
                    },
                    buttons: {
                        "Cancel": function(){
                            $(this).dialog("close");
                        },
                        "Ok": function() {
                            var t=$(this);
                            $.ajax({
                                data:{
                                    'resize': url,
                                    'width': $('#wysiwyg-image-edit-resize-'+index+' .size b:first').html(),
                                    'postfix': '_m'
                                },
                                success:function(r){
                                    if(r.ok!=undefined){
                                        url_m=r.ok;
                                        
                                        if (url_m&&url_m.length>0){
                                            img=new Image();
                                            img.onload=function(){
                                                align=$(wind+' .align').val();
                                                margin=$(wind+' .margin').val();
                                                if(margin=='') margin=0;
                                                image.after('<a href="'+url+'"><img src="'+url_m+'" align="'+align+'" style="margin:'+margin+'px;" /></a>');
                                                image.next().wysiwyg_img();
                                                image.remove();
                                                setTimeout(function(){
                                                    i2t();
                                                }, 100);
                                                t.dialog("close");
                                                i2t();
                                            }
                                            img.src=url_m;
                                            
                                        }
                                    }
                                }
                            });
                        }
                    },
                    close:function(){
                        $(wind+' .image').val('');
                        $(wind+' .url').val('');
                        $(wind+' .margin').val('');
                    }
                });
            }
            else{
                $(wind).dialog('open');
            }
        });
    }
    $.fn.wysiwyg_a=function(index){
        $(this).unbind('dblclick').dblclick(function(){
            wind='#wysiwyg-url-edit-'+index;
            a=$(this);
            if(!$(wind).length){                
                var value='<div id="wysiwyg-url-edit-'+index+'">'
                +'<div><label>Title:</label><input class="title" type="text" /></div>'
                +'<div><label>URL:</label><input class="url" name="url" type="text" /></div>'
                +'</div>';
                $('#windows').append(value);
                $(wind).dialog({
                    autoOpen: true,
                    width: 300,
                    open:function(){
                        href=a.attr('href');
                        title=a.attr('title');
                        $(wind+' .url').val(href);
                        $(wind+' .title').val(title);
                    },
                    buttons: {
                        "Cancel": function(){
                            $(this).dialog("close");
                        },
                        "Ok": function() {
                            var url = $(wind+' .url').val();
                            var title = $(wind+' .title').val();
                            if (url && url.length > 0 ){
                                if(title=='') title=url;
                                a.attr('href', url);
                                a.attr('title', title);
                                a.wysiwyg_a();
                            }
                            $(wind+' .url').val('');
                            $(wind+' .title').val('');
                            $(this).dialog("close");
                            i2t();
                            iframe.focus();
                        }
                    },
                    closeOnEscape: true
                });
            }
            else{
                $(wind).dialog('open');
            }
        });
    }
})(jQuery);